package lib

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	QrLoadUrl string = "http://www.ymiot.net/BizCouponSolution/QRcodeLoad" //加载优惠券二维码
)

type QrLoadRequest struct {
	CouponSolutionID int `json:"CouponSolution_ID"`
}

// QRCodeLoad 加载优惠券
func QRCodeLoad(client http.Client, request QrLoadRequest, ctx RequestContext) (*QrLoadResponse, error) {
	r, err := http.NewRequest("POST", QrLoadUrl,
		bytes.NewReader([]byte(fmt.Sprintf("CouponSolution_ID=%d", request.CouponSolutionID))))
	if err != nil {
		return nil, err
	}

	SetHeader(r)
	ctx.SetHttpCookie(r)
	resp, err := client.Do(r)
	if err != nil {
		return nil, err
	}

	defer func() {
		_ = resp.Body.Close()
	}()
	respData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var rev QrLoadResponse
	err = json.Unmarshal(respData, &rev)
	if err != nil {
		return nil, err
	} else {
		return &rev, nil
	}
}
